import * as React from 'react';
import classNames from 'classnames';
import DescriptionsItem from './Item';


export interface DescriptionsProps {
	children?: React.ReactNode;
	className?: string;
	title?: string;
	column?: number;
}

interface DescriptionsType extends React.FC<DescriptionsProps> {
	Item: typeof DescriptionsItem;
}

function getDescriptionsTrItem(list:any, trIndex:number): React.ReactElement {
	return React.cloneElement(
		<tr className="bh-descriptions-row" key={trIndex}>
	        {list}
		</tr>
	)
}

function getDescriptionsInterItem(node: any, index:number): React.ReactElement {
	const {
		children,
		label
	} = node.props;

	return React.cloneElement(
		<td className="bh-descriptions-item" key={index}>
			<div className="bh-descriptions-item-container">
	        	<span className="bh-descriptions-item-label">{label}</span>
	        	<span className="bh-descriptions-item-content">
	        		{children}
	        	</span>
	        </div>
		</td>
	)
}
function getRows(children: React.ReactNode, column: number) {
	const childNodes = Array.prototype.slice.call(children)
	const rows: React.ReactElement[] = [];
	let tmpRow: React.ReactElement[] = [];
	let rowRestCol = column;
	let rowIndex = 1;//tr的key,第几行
	childNodes.forEach((node, index) => {
		if(rowRestCol) {
			tmpRow.push(getDescriptionsInterItem(node, index));
			rowRestCol--;
		}

		//一轮完成||最后一轮未满
		if(rowRestCol == 0 || rowRestCol && index == childNodes.length - 1) {
			rows.push(getDescriptionsTrItem(tmpRow, rowIndex++));
			rowRestCol = column;
			tmpRow = [];
		}
	});
	
	return rows;
}

const Descriptions: DescriptionsType = props => {
	const prefixCls = 'bh-descriptions';
	const {
		children,
		className,
		title,
		column = 3,
		...restProps
	} = props;
	const classString = classNames(
		prefixCls,
		className,
	);
	const rows = getRows(children, column);

	return (
		<div {...restProps} className={classString}>
		    <div className="bh-descriptions-header">
		    	<div className="bh-descriptions-title">{title}</div>
		    </div>
		    <div className="bh-descriptions-view">
		    	<table>
		    		<tbody>
		    		    {rows}
		    	    </tbody>
		    	</table>
		    </div>
		</div>
	)
};

Descriptions.Item = DescriptionsItem;

export default Descriptions;